<?php


namespace app\app\controller;


use app\constant\BillConst;
use app\constant\DistriConst;
use app\constant\OrderConst;
use app\constant\RewardConst;
use app\helper\OrderHelper;
use app\libs\Utils;
use app\model\AdminDistridetail;
use app\model\AdminOrder;
use app\model\AdminOrderItem;
use app\model\AdminReward;
use app\model\AppUserBill;
use app\model\AppUserWallet;
use app\util\ReturnCode;
use Exception;
use think\Db;
use think\facade\Log;

class StoreAdminOrder extends BaseStoreAdmin
{
    public function getOrderByCode()
    {
        $orderItemId = $this->request->get('code');//这里的code是已经通过AppGetStoreByCode解密过的
        if (!isset($orderItemId)) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的参数');
        }
        $orderItemModel = AdminOrderItem::get($orderItemId);
        if ($orderItemModel) {
            if ($orderItemModel->is_finish === OrderConst::ORDER_ITEM_IS_FINISH) {
                return $this->buildFailed(ReturnCode::FAILED, '已经核销过了，请不要重复核销');
            }
            $orderModel = AdminOrder::get($orderItemModel->order_id);
            if ($orderModel) {
                $orderData = $orderModel->getData();
                //判断订单状状态
                if (OrderHelper::orderIsPaidAndNormal($orderData)) {
                    $orderData['item_data'] = $orderItemModel->getData();
                    return $this->buildSuccess($orderData);
                } else {
                    return $this->buildFailed(ReturnCode::FAILED, '当前订单状态不可进行核销');
                }
            }
        }
        return $this->buildFailed(ReturnCode::FAILED, '获取失败');
    }


    /**
     * 核销
     * 这里要注意几个点，
     * 1、核销的时候要检测用户权限（权限会在路由中做检测）
     * 2、核销的时候要记录当前操作的用户
     * 3、核销完等就是完成交易了，要把订单状态作一下变更
     * 4、订单如果涉及到分销的，要在分销表里把对应的分销金额确定
     * @return \think\response\Json
     */
    public function checkCode()
    {
        $orderItemId = $this->request->get('code');//这里的code是已经通过AppGetStoreByCode解密过的
        if (!isset($orderItemId)) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的参数');
        }
        $orderItemModel = AdminOrderItem::get($orderItemId);
        if ($orderItemModel->is_finish === OrderConst::ORDER_ITEM_IS_FINISH) {
            return $this->buildFailed(ReturnCode::FAILED, '已经核销过了，请不要重复核销');
        }
        $orderModel = AdminOrder::get($orderItemModel->order_id);
        if ($orderModel) {
            //判断订单状状态
            if (!OrderHelper::orderIsPaidAndNormal($orderModel->getData())) {
                return $this->buildFailed(ReturnCode::FAILED, '当前订单状态不可进行核销');
            }
            Db::startTrans();
            try {
                //1、更新当前订单状态
                $orderItemModel->setAttr('is_finish', OrderConst::ORDER_ITEM_IS_FINISH);
                $orderItemModel->setAttr('finish_time', new \DateTime());
                $orderItemModel->setAttr('op_wx_user_name', $this->storeUserInfo['name']);
                $orderItemModel->setAttr('op_wx_user_id', $this->userInfo['uid']);
                $affected = $orderItemModel->allowField(true)->save();
                if ($affected) {
                    //更新成功
                    //2、处理主订单表，这里只需要查询一下还有没有子订单表未核销就行了
                    $has = AdminOrderItem::get(['order_id' => $orderModel->id, 'is_finish' => OrderConst::ORDER_ITEM_UN_FINISH, 'status' => OrderConst::ORDER_ITEM_STATUS_NORMAL]);
                    if (!$has) {
                        $orderModel->setAttr('trade_status', OrderConst::ORDER_STATUS_USED);
                        $done = $orderModel->allowField(true)->save();
                        if (!$done) {
                            throw new \Exception('更新订单状态失败');
                        }
                        //3、分销处理
                        $disModel = AdminDistridetail::get(['tid'=>$orderModel->tid,'order_id'=>$orderModel->id,'order_item_id'=>$orderItemModel->id]);
                        if($disModel){
                            $disModel->setAttr('status',DistriConst::STATUS_CAN_EXTRACT);
                            $disModel->allowField(true)->save();
                            $income=$disModel->money;
                            // 增加余额
                            if($income>0){
                                (new AppUserWallet())->where(['tid'=>$disModel->tid,'uid'=>$disModel->uid])->inc('income',$income)->inc('total_income',$income)->update();
                            }
                            //3-1增加记录
                            AppUserBill::toSave($orderModel->tid,$disModel->uid,$disModel->money,BillConst::TYPE_INCOME,BillConst::INCOME_TYPE_DISTRIBUTION,'分销');
                        }
                        //推广赏金处理
                        if(!Utils::isEmpty($orderModel->invid)){
                            $rewardModel = AdminReward::get(['tid'=>$orderModel->tid,'order_id'=>$orderModel->id,'order_item_id'=>$orderItemModel->id]);
                            $rewardModel->setAttr('status',RewardConst::STATUS_CAN_EXTRACT);
                            $rewardModel->allowField(true)->save();
                            $income=$rewardModel->money;
                            // 增加余额
                            if($income>0){
                                (new AppUserWallet())->where(['tid'=>$rewardModel->tid,'uid'=>$rewardModel->uid])->inc('income',$income)->inc('total_income',$income)->update();
                            }
                            //3-2增加记录
                            AppUserBill::toSave($rewardModel->tid,$rewardModel->uid,$rewardModel->money,BillConst::TYPE_INCOME,BillConst::INCOME_TYPE_REWORD,'推广');
                        }

                        Db::commit();
                        return $this->buildSuccess(null);
                    }
                }
            } catch (Exception $e) {
                Log::error('核销出错'.$e->getMessage(),['code'=>$orderItemId]);
            }
            Db::rollback();
        }
        return $this->buildFailed(ReturnCode::FAILED, '核销失败');
    }
}